import React, { Component } from "react";
import { StyleSheet, View, Text, TouchableOpacity } from "react-native";

import { connect } from "react-redux";
import HeaderDefault from "../../components/header/HeaderDefault";
import Toast from "react-native-simple-toast";
import { theme_app, theme_text } from "../../utils/appTheme";
import QRCodeScanner from "react-native-qrcode-scanner";
import Torch from "react-native-torch";

class SignScan extends Component {
  constructor(props) {
    super(props);
    this.state = {
      viewAppear: false,
      torchIsOpen: false
    };

    this.onSuccess = this.onSuccess.bind(this);
  }
  static navigationOptions = ({ navigation }) => ({
    header: (
      <HeaderDefault
        title={
          navigation.state.params.qrTitle
            ? navigation.state.params.qrTitle
            : "扫描二维码"
        }
        backBtnOnPress={() => {
          navigation.goBack();
        }}
      />
    )
  });

  onSuccess(e) {
    let aStr = e.data;

    // {"pno":"073aed4d1c7b3ae12e15fe6a55e9700d","bedId":"216","type":"bedSideCard"}
    try {
      let type = aStr.substring(0, 1);
      let valueStr = aStr.substring(1);

      if (type) {
        this._scanSuccess(type, valueStr);
      } else {
        this._ScanFaile("该二维码异常");
      }
    } catch (error) {
      this._ScanFaile("该二维码异常");
    }
  }

  _scanSuccess(type, scanData) {
    let { nextRouter } = this.props.navigation.state.params;
    this._closeTorch();

    // 配药/配药复核
    if (
      nextRouter === "DispenseResult" ||
      nextRouter === "DispenseReviewResult"
    ) {
      if (type === "A") {
        let adviseNo = scanData;
        let params = {
          ...this.props.navigation.state.params,
          currentRouterKey: this.props.navigation.state.key,
          adviseNo
        };
        this.props.navigation.navigate(nextRouter, params);
      } else {
        this._ScanFaile("未能处理该类型二维码");
      }
    }

    // 输液执行
    else if (nextRouter === "InfusionResult") {
      this._optionPT(type, scanData);
    } else if (nextRouter === "OxygenAdd" || nextRouter === "ConventionAdd") {
      this._handleOxygenAdd(type, scanData, nextRouter);
    }

    // 其他
    else {
      this._ScanFaile("未能处理该类型二维码");
    }
  }

  // 常规、吸氧巡视扫码处理
  _handleOxygenAdd = (type, scanData, aNextRouter) => {
    if (type === "W" || type === "B") {
      let pno = scanData;

      let titleName = aNextRouter === "OxygenAdd" ? "添加吸氧巡视" : "常规巡视";

      this.props.navigation.navigate(aNextRouter, {
        title: titleName,
        commitSuccessCB: () => { this.refs.qrScan.reactivate(); },
        isEditer: false,
        currentRouterKey: this.props.navigation.state.key,
        pinfo: {
          patient_no: pno
        }
      });
    } else {
      this._ScanFaile("未能处理该类型二维码");
    }
  };

  _optionPT = (type, scanData) => {
    if (!this.goBackForRepartString && type === "A") {
      if (scanData !== this.props.navigation.state.params.adviseNo) {
        this._ScanFaile("瓶贴二维码不正确");
      } else {
        let params = {
          ...this.props.navigation.state.params,
          currentRouterKey: this.props.navigation.state.key,
          adviseNo: this.props.navigation.state.params.adviseNo,
          opt: "first",
          callBackFun: this._goBackForRepeat
        };
        this.props.navigation.navigate(
          this.props.navigation.state.params.nextRouter,
          params
        );
      }
    } else if (this.goBackForRepartString && (type === "W" || type === "B")) {
      // code

      let pno = scanData;
      if (pno !== this.props.navigation.state.params.patient_no) {
        this._ScanFaile("请扫码正确的疗养员二维码");
      } else {
        let params = {
          ...this.props.navigation.state.params,
          currentRouterKey: this.props.navigation.state.key,
          adviseNo: this.props.navigation.state.params.adviseNo,
          opt: "second"
        };
        this.props.navigation.navigate(
          this.props.navigation.state.params.nextRouter,
          params
        );
      }
    } else {
      this._ScanFaile("未能处理该类型二维码");
    }
  };

  _ScanFaile(msg) {
    Toast.showWithGravity(msg, 0.3, Toast.CENTER);
    this.refs.qrScan.reactivate();
  }

  _goBackForRepeat = markStr => {
    this.goBackForRepartString = markStr;
    this.refs.qrScan.reactivate();
  };

  _closeTorch = () => {
    if (this.state.torchIsOpen) {
      Torch.switchState(false);
      this.setState({ torchIsOpen: false });
    }
  };

  render() {
    return (
      <QRCodeScanner
        ref="qrScan"
        onRead={this.onSuccess.bind(this)}
        showMarker={true}
        topContent={<Text style={styles.centerText}>请扫描二维码</Text>}
        bottomContent={
          <TouchableOpacity
            onPress={() => {
              let isOpen = !this.state.torchIsOpen;
              Torch.switchState(isOpen);
              this.setState({ torchIsOpen: isOpen });
            }}
            style={styles.buttonTouchable}
          >
            <Text style={styles.buttonText}>
              {this.state.torchIsOpen ? "关闭手电筒" : "打开手电筒"}
            </Text>
          </TouchableOpacity>
        }
      />
    );
  }
}
const styles = StyleSheet.create({
  centerText: {
    flex: 1,
    fontSize: 18,
    padding: 32,
    color: "#777"
  },
  textBold: {
    fontWeight: "500",
    color: "#000"
  },
  buttonText: {
    fontSize: theme_text.default_font
  },
  buttonTouchable: {
    padding: 16
  }
});

function select(store) {
  return {};
}

export default connect(select)(SignScan);
